#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <stdio.h>
#include <stdlib.h>

void ip_convert(const char *ip, const char *port) {
    in_addr_t net_addr;
    uint16_t net_port;
    uint16_t host_port;

    // 1.将IP转换成网络字节序
    net_addr = inet_addr(ip);

    if (net_addr == INADDR_NONE) {
        perror("Fail to inet_addr");
        exit(EXIT_FAILURE);
    }

    printf("net_addr: %#x\n", net_addr);

    // 2.获取网络字节序的端口 host to network short
    net_port = htons(atoi(port));
    printf("net_port: %#x\n", net_port);

    //3. 网络字节序转ip
    struct in_addr addr;
    addr.s_addr = net_addr;
    printf("host ip = %s\n", inet_ntoa(addr));

    // 4. 网络字节序的端口 转换成主机端口 network to host short
    host_port = ntohs(net_port);
    printf("host_port = %d\n", host_port);
}
int main(int argc, char const *argv[])
{
    ip_convert("127.0.0.1", "8080");
    return 0;
}
